<template>
  <div class="post-detail">
    <div class="post-detail">
      <h2>{{ post?.title || '帖子未找到' }}</h2>
      <!-- 使用 flex 布局 -->
      <div class="post-header">
        <el-button type="text" size="large" @click="goToProfile(post?.stu_id)" :style="{ fontSize: '16px' }">
          {{ post?.stu_id || '未知用户' }}
        </el-button>
        <p class="course-info">发布于 {{ post?.createdAt || '未知时间' }}</p>
      </div>
      <p class="post-content">{{ post?.content || '暂无内容' }}</p>
    </div>
    <!-- 帖子操作按钮 -->
    <div class="post-actions">
      <div class="post-actions">
        <el-button :type="isFollowed ? 'danger' : 'primary'" @click="toggleFollow">
          {{ isFollowed ? '取消收藏' : '收藏' }}
        </el-button>
        <el-button @click="toggleReplyInput">回复</el-button>
      </div>
    </div>

    <!-- 回复列表 -->
    <div class="replies">
      <h3>共 {{ replies.length }} 个回复</h3>
      <div v-for="reply in replies" :key="reply.reply_id" class="reply-item">
        <div class="reply-author">
          <el-button type="text" size="large" @click="goToProfile(reply.user_id)" :style="{ fontSize: '16px' }">
            {{ reply.user_id }}
          </el-button>
          <span>{{ reply.createdAt }}</span>
        </div>
        <p>{{ reply.content }}</p>
        <div class="reply-actions">
          <span>👍 {{ reply.likes }}
            <el-button type="text" @click="toggleLikeReply(reply)">
              {{ reply.liked ? '取消点赞' : '点赞' }}
            </el-button>
          </span>
        </div>
      </div>
    </div>

    <!-- 回复输入框 -->
    <div v-show="showReplyInput" class="reply-input">
      <el-input v-model="newReplyContent" type="textarea" rows="3" placeholder="请输入回复内容"></el-input>
      <el-button type="primary" @click="submitReply">发表回复</el-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { BASE_URL } from '@/config';

export default {
  data() {
    return {
      post: {},               // 帖子详情数据
      replies: [],            // 帖子回复数据
      showReplyInput: false,  // 控制回复输入框的显示
      newReplyContent: '',     // 新回复内容
      isFollowed: false,
    };
  },
  created() {
    this.fetchPost();    // 获取帖子详情
    this.fetchReplies(); // 获取回复列表
    this.checkFollowStatus(); // 检查关注状态
  },
  methods: {
    // 获取帖子详情
    fetchPost() {
      const postId = this.$route.params.id;
      if (!postId) {
        console.error('postId is missing');
        return;
      }

      axios.post(`${BASE_URL}/posts/getCurrentPost`, {post_id: postId})
          .then(response => {
            if (response.data.code === 200) {
              this.post = response.data.data || {};
              console.log('帖子详情:', this.post);
            } else {
              console.error('获取帖子详情失败:', response.data.message);
              this.post = {};
            }
          })
          .catch(error => {
            console.error('请求帖子详情失败:', error);
            this.post = {};
          });
    },
    // 检查是否已收藏帖子
    checkFollowStatus() {
      const postId = this.$route.params.id;
      const userId = window.sessionStorage.getItem('userId');
      console.log("检查收藏帖子", postId, userId);

      if (!userId || !postId) return;

      axios.post(`${BASE_URL}/posts/isFavorite`, {user_id: userId, post_id: postId})
          .then(response => {
            if (response.data.code === 200) {
              this.isFollowed = response.data.data; // 后端返回布尔值
            }
          })
          .catch(() => {
            this.isFollowed = false;
          });
    },

    // 收藏或取消收藏
    toggleFollow() {
      const postId = this.$route.params.id;
      const userId = window.sessionStorage.getItem('userId');

      if (!userId) {
        this.$message.error('用户未登录');
        return;
      }

      const apiUrl = this.isFollowed ? `${BASE_URL}/posts/unfavorite` : `${BASE_URL}/posts/favorite`;
      axios.post(apiUrl, {user_id: userId, post_id: postId})
          .then(response => {
            if (response.data.code === 200) {
              this.isFollowed = !this.isFollowed;
              this.$message.success(this.isFollowed ? '收藏成功' : '取消收藏成功');
            } else {
              this.$message.error(this.isFollowed ? '取消收藏失败' : '收藏失败');
            }
          })
          .catch(() => {
            this.$message.error(this.isFollowed ? '取消收藏失败' : '收藏失败');
          });
    },


    // 获取回复列表并检查点赞状态
    fetchReplies() {
      const postId = this.$route.params.id;
      if (!postId) {
        console.error('postId is missing');
        return;
      }

      axios.post(`${BASE_URL}/replies/replyList`, {post_id: postId})
          .then(response => {
            if (response.data.code === 200) {
              this.replies = response.data.data.map(reply => ({
                ...reply,
                liked: false // 初始化 liked 状态为 false
              }));
              this.checkLikes(postId);
            } else {
              console.error('获取回复列表失败:', response.data.message);
              this.replies = [];
            }
          })
          .catch(error => {
            console.error('请求回复列表失败:', error);
            this.replies = [];
          });
    },

    // 检查点赞状态
    checkLikes(postId) {
      const userId = window.sessionStorage.getItem('userId');
      if (!userId) {
        console.error('用户未登录');
        return;
      }

      axios.post(`${BASE_URL}/replies/checkLikes`, {user_id: userId, post_id: postId})
          .then(response => {
            console.log('检查点赞状态响应数据:', response.data);

            if (response.data.code === 200) {
              const likedReplies = response.data.data || [];

              // 更新每个回复的点赞状态
              this.replies.forEach(reply => {
                if (likedReplies.includes(reply.reply_id)) {
                  reply.liked = true;
                }
              });

              console.log('更新后的回复列表:', this.replies);
            } else {
              console.error('检查点赞状态失败:', response.data.message);
            }
          })
          .catch(error => {
            console.error('检查点赞状态请求失败:', error);
          });
    },

    // 点赞或取消点赞回复
    toggleLikeReply(reply) {
      const userId = window.sessionStorage.getItem('userId');
      if (!userId) {
        this.$message.error('请先登录');
        return;
      }

      const apiUrl = reply.liked ? `${BASE_URL}/replies/unlike` : `${BASE_URL}/replies/like`;
      axios.post(apiUrl, {reply_id: reply.reply_id, user_id: userId})
          .then(response => {
            if (response.data.code === 200) {
              reply.liked = !reply.liked;
              reply.likes += reply.liked ? 1 : -1;
              this.$message.success(reply.liked ? '点赞成功' : '取消点赞成功');
            } else {
              this.$message.error(reply.liked ? '取消点赞失败' : '点赞失败');
            }
          })
          .catch(error => {
            console.error(reply.liked ? '取消点赞失败' : '点赞失败:', error);
          });
    },

    // 切换回复输入框
    toggleReplyInput() {
      this.showReplyInput = !this.showReplyInput;
    },

    // 提交回复
    submitReply() {
      if (!this.newReplyContent) {
        this.$message.error('回复内容不能为空');
        return;
      }

      const userId = window.sessionStorage.getItem('userId');
      const postId = this.$route.params.id;

      axios.post(`${BASE_URL}/replies/createReply`, {
        post_id: postId,
        content: this.newReplyContent,
        user_id: userId
      })
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('回复成功');
              this.fetchReplies(); // 刷新回复列表
              this.newReplyContent = '';
            } else {
              this.$message.error('回复失败');
            }
          })
          .catch(error => {
            console.error('提交回复失败:', error);
          });
    },

    // 删除帖子
    confirmDeletePost() {
      this.$confirm('确定要删除该帖子吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deletePost();
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    deletePost() {
      const postId = this.$route.params.id;
      axios.post(`${BASE_URL}/posts/delete`, {post_id: postId})
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('帖子已删除');
              const userId = window.sessionStorage.getItem('userId');
              this.$router.push(`/TeacherCourse/${userId}`);
            } else {
              this.$message.error('删除帖子失败');
            }
          })
          .catch(error => {
            console.error('删除帖子失败:', error);
          });
    },

    goToProfile(profileuser_id) {
      this.$router.push({
        name: 'ProfilePage',
        query: {profileuser_id, user_id: window.sessionStorage.getItem('userId')}
      });
    }

  }
};
</script>

<style scoped>
.post-detail {
  padding: 20px;
}

.course-info {
  color: #888;
  font-size: 14px;
}

.post-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.replies {
  margin-top: 20px;
}

.reply-item {
  border-top: 1px solid #eee;
  padding: 10px 0;
}

.reply-actions {
  display: flex;
  gap: 10px;
  color: #888;
  font-size: 14px;
}

.reply-input {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
  width: 100%;
}

.post-detail {
  padding: 20px;
  background-color: #f9f9f9;
}

.post-header {
  display: flex; /* 启用 Flex 布局 */
  align-items: center; /* 垂直居中对齐 */
  gap: 10px; /* 增加间距 */
}

.course-info {
  color: gray;
  font-size: 14px;
}

.post-content {
  line-height: 1.6;
  margin-top: 20px;
}

.post-detail {
  padding: 20px;
}

.post-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.replies {
  margin-top: 20px;
}

.reply-item {
  border-top: 1px solid #eee;
  padding: 10px 0;
}

.reply-actions {
  display: flex;
  gap: 10px;
  color: #888;
  font-size: 14px;
}
</style>
